<template>
    <div style="padding: 20px">
        <!-- 文件上传 -->
        <el-upload action="#" multiple :auto-upload="false" :on-change="handleFileChange" :show-file-list="false">
            <el-button type="primary">上传文件</el-button>
        </el-upload>

        <!-- 表格展示文件信息 -->
        <el-table :data="fileList" border style="margin-top: 20px">
            <el-table-column prop="name" label="文件名"></el-table-column>
            <el-table-column label="段号">
                <template #default="{ row }">
                    <el-select v-model="row.selectedSegments" multiple placeholder="请选择段号">
                        <el-option v-for="segment in segmentOptions" :key="segment" :label="segment" :value="segment" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="备注">
                <template #default="{ row }">
                    <div style="display: flex; flex-wrap: wrap; gap: 5px; align-items: center">
                        <el-tag v-for="(tag, index) in row.tags" :key="index" closable @close="removeTag(row, index)"
                            size="small">
                            {{ tag }}
                        </el-tag>
                        <el-input v-model="row.newTag" placeholder="+ 添加" size="small" style="width: 80px"
                            @keyup.enter="addTag(row)" @blur="addTag(row)" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    <span :style="{ color: row.status === '成功' ? 'green' : row.status === '失败' ? 'red' : '' }">
                        {{ row.status }}
                    </span>
                </template>
            </el-table-column>
        </el-table>

        <!-- 提交按钮 -->
        <el-button type="success" @click="submitFiles" style="margin-top: 20px">提交上传</el-button>
    </div>
</template>

<script setup>
import { ref } from 'vue';

// 所有可用段号
const segmentOptions = Array.from({ length: 34 }, (_, i) => (i + 1).toString());

// 存储文件列表
const fileList = ref([]);

// 处理文件上传变化
const handleFileChange = (file, uploadFiles) => {
    const exists = fileList.value.some(f => f.uid === file.uid);
    if (!exists && file.status !== 'removed') {
        fileList.value.push({
            uid: file.uid,
            name: file.name,
            selectedSegments: [],
            tags: [],
            newTag: '', // 用于新增 tag 的输入框
            status: '',
            rawFile: file.raw
        });
    }
};

// 删除 tag
const removeTag = (row, index) => {
    row.tags.splice(index, 1);
};

// 添加新的 tag
const addTag = (row) => {
    const trimmed = row.newTag.trim();
    if (trimmed && !row.tags.includes(trimmed)) {
        row.tags.push(trimmed);
    }
    row.newTag = '';
};

// 提交上传
const submitFiles = async () => {
    // 清空旧的状态
    fileList.value.forEach(row => {
        row.status = '';
    });

    // 校验段号是否重复
    const segmentMap = new Map();

    for (let row of fileList.value) {
        if (!row.selectedSegments.length) {
            row.status = '未选段号';
            continue;
        }

        // 检查段号是否有重复
        for (let seg of row.selectedSegments) {
            if (segmentMap.has(seg)) {
                row.status = `段号${seg}冲突`;
                segmentMap.get(seg).status = `段号${seg}冲突`;
            } else {
                segmentMap.set(seg, row);
            }
        }
    }

    // 如果存在冲突或未选段号的项，不继续上传
    const hasError = fileList.value.some(row => row.status);
    if (hasError) {
        alert('请修正段号冲突或未选择段号的文件后再提交');
        return;
    }

    // 开始上传
    for (let row of fileList.value) {
        row.status = '上传中...';
        try {
            await uploadFileToServer(row.rawFile, row.selectedSegments, row.tags);
            row.status = '成功';
        } catch (e) {
            console.error(e);
            row.status = '失败';
        }
    }
};

// 模拟上传接口函数
const uploadFileToServer = (file, segments, tags) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.2) {
                resolve({ success: true });
            } else {
                reject(new Error('上传失败'));
            }
        }, 1000); // 模拟网络延迟
    });
};
</script>

<style scoped>
.el-select {
    width: 100%;
}
</style>